package com.lwt.db137.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.lwt.db137.bean.User;
import com.lwt.db137.commen.JwtUtils;
import com.lwt.db137.commen.R;
import com.lwt.db137.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;


/**
 * @author lwt
 * @version 1.0
 * @Description
 * @date 2024/12/24 11:43
 */
@CrossOrigin(origins = "*")
@RestController
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("user")
    public R getUser(@RequestBody User user){
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.setEntity(user);
        User u = userService.getOne(queryWrapper);
        if(u!=null) {
            //生成token
            HashMap<String, Object> map = new HashMap<>();
            map.put("userid",u.getId());
            String jwtToken = JwtUtils.createJwtToken(map);
            System.out.println("jwtToken = " + jwtToken);
            return new R().addData("token",jwtToken);
            }
        return new R().setMsgrr("出错了").setCode(500);
    }
    @GetMapping("menu")
    public R getMenu(@RequestHeader("token") String token){
        //解析token
        System.out.println("token = " + token);
        Integer userid = JwtUtils.getJwtToken(token, "userid");
        System.out.println("userid = " + userid);
        User byId = userService.getById(userid);
        System.out.println("byId = " + byId);
        return new R().addData("menu",userService.getMenuList(userid)).addData("username",byId);

    }
    //注册
    @PostMapping("userAdd")
    public int userAdd(@RequestBody User user){
        System.out.println("user = " + user);
        return userService.addUser(user);
    }
    //查询所有用户
    @GetMapping("userList")
    public R userList(){
        return new R().addData("userList",userService.list());
    }
}
